package com.masterlu.leetcode.daily.linkedlist.simple;

import com.masterlu.leetcode.daily.linkedlist.ListNode;

import java.util.HashSet;

/**
 * 相交链表
 * https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
 *
 * @Author：masterlu
 * @Date：2021/4/13 11:25 上午
 */
public class S160GetIntersectionNode {

    /**
     * 借助HashSet保存
     *
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        HashSet<ListNode> listNodes = new HashSet<>();
        while (headA != null || headB != null) {
            if (null != headA) {
                if (!listNodes.add(headA)) {
                    return headA;
                }
                headA = headA.next;
            }

            if (null != headB) {
                if (!listNodes.add(headB)) {
                    return headB;
                }
                headB = headB.next;
            }
        }
        return null;
    }


}
